/**
 *
 */
package cn.ipenta.core.utils;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @author ipenta
 * @ClassName: BeanUtils
 * @Description: TODO
 * @date 2017年4月16日 下午8:16:23
 */
public class BeanUtils extends org.springframework.beans.BeanUtils {

	public static String buildUUID() {
		String s = UUID.randomUUID().toString();
		//去掉“-”符号
		return s.toString().replace("-", "");
	}

	public static String getRandomString(int length) { //length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static <T> Map<String, Object> beanToMap(T t) {

		Map<String, Object> m = new HashMap<>();

		BeanWrapper beanWrapper = new BeanWrapperImpl(t);
		PropertyDescriptor[] descriptors = beanWrapper.getPropertyDescriptors();
		for (PropertyDescriptor descriptor :descriptors) {
			String name = descriptor.getName();
			if (!name.equals("class")){
				m.put(name, beanWrapper.getPropertyValue(name));
			}
		}
		return m;
	}
}
